

#include "http_server.h"
#include "session.h"
#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/system/detail/error_code.hpp>
#include <cstdint>
#include <memory>


HttpServer::HttpServer(boost::asio::io_context & io_context):m_context(io_context),m_acceptor(io_context),m_socket(io_context)
{
	m_acceptor.bind(boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 9099));
	m_acceptor.listen();
}

void HttpServer::AcceptConnection()
{
	m_acceptor.async_accept(m_socket,[this](boost::system::error_code & ec){

		if (!ec)
		{
			int64_t id = m_id.fetch_add(1);
			auto session = std::make_shared<Session>(m_context, this, id, m_socket);
			m_session_map[id] = session;
			session->StartSession();

			AcceptConnection();
		}

	});
}

void HttpServer::RemoveSession(std::int64_t id)
{
	m_session_map.erase(id);
}